<template>
  <div class="market-guide-wrapper">
    <p class="title">综合查询</p>
    <div class="form-search-area">
      <el-form :inline="true" :model="formInline" size="medium" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="formInline.titleLike" placeholder="请输入标题" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="medium" @click="searchOrg">查询</el-button>
          <el-button size="medium" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="right-btn-area">
        <el-button size="medium" type="primary" @click="popNewAddDialog">新增</el-button>
      </div>
    </div>
    <!-- 表格 开始-->
    <div class="table-area clearfix">
      <el-table ref="multipleTable" v-loading="loading" :data="tableData" stripe @selection-change="selectionChange">
        <el-table-column label="序号" width="50">
          <template slot-scope="scope">{{ scope.$index + startNum + 1 }}</template>
        </el-table-column>
        <el-table-column label="标题" prop="title"></el-table-column>
        <el-table-column label="分类目录" prop="catalog"></el-table-column>
        <el-table-column label="发布日期" prop="releaseDate"></el-table-column>
        <el-table-column label="发布审核人" prop="reviewer"></el-table-column>
        <el-table-column label="操作" min-width="100px">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.guideId)">查看</el-link>
            <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.guideId)">编辑</el-link>
            <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.guideId)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="paging-self"
        background
        :current-page.sync="currentPage"
        layout="total, prev, pager, next"
        :total="totalCount"
        @current-change="pageChange">
      </el-pagination>
    </div>
    <!-- 表格 结束-->
    <!-- 对话框 开始 -->
    <el-dialog title="超市指南" :visible.sync="dialogFormVisible" width="80vw" top="5vh" @closed="closeDialog" :close-on-click-modal="false">
      <el-form ref="ruleDialog" :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="dialogForm.title" placeholder="请输入标题" autocomplete="off" clearable maxlength="250"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类目录" prop="catalog">
              <el-input v-model="dialogForm.catalog" placeholder="请输入分类目录" autocomplete="off" clearable maxlength="250"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发布日期" prop="releaseDate">
              <el-date-picker
                v-model="dialogForm.releaseDate"
                type="date"
                placeholder="请选择发布日期"
                clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布审核人" prop="reviewer">
              <el-input v-model="dialogForm.reviewer" placeholder="请输入发布审核人" autocomplete="off" clearable maxlength="250"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dialogForm.remark" placeholder="请输入备注" autocomplete="off" maxlength="250"></el-input>
        </el-form-item>
        <el-form-item label="附件" prop="enclosure">
          <el-upload
            class="upload-demo"
            :file-list="fileListPic"
            ref="annex"
            :action="uploadUrl"
            :before-upload="beforePicUpload"
            :on-success="uploadPicSuccess"
            :on-preview="handlePicPreview"
            :on-remove="handlePicRemove">
            <el-button size="small" type="primary">点击上传附件</el-button>
            <div slot="tip" class="el-upload__tip"></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="正文" prop="content">
          <div v-show="dialogMode===CNST.READ_MODE" v-html="dialogForm.content" class="read-text"></div>
          <tinymce v-show="dialogMode!==CNST.READ_MODE" v-model="dialogForm.content" :height="350"></tinymce>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogMode!==CNST.READ_MODE" type="primary" @click="submitOrg">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import Bus from '@/utils/Bus'
import {
  getCoreGuideList,
  getCoreGuideDetail,
  addCoreGuide,
  updateCoreGuide,
  deleteCoreGuide
} from '@/api/agencyService'
import { deepClone, convertDateToString } from '@/utils'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'MarketGuide',
  components: { Tinymce },
  data() {
    return {
      formInline: {
        titleLike: ''
      },
      loading: false,
      tableData: [],
      dialogMode: '', // 对话框的状态，新增，查看，编辑
      curId: '', // 点击查看或编辑的当前列表项的id
      totalCount: 0, // 总共多少条
      currentPage: 1, // 分页当前页
      dialogFormVisible: false,
      dialogForm: {
        title: '',
        catalog: '',
        releaseDate: '',
        reviewer: '',
        remark: '',
        enclosure: '',
        content: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        catalog: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
        releaseDate: [{ required: true, message: '请选择发布日期', trigger: 'change' }],
        reviewer: [{ required: true, message: '请输入审核人', trigger: 'blur' }]
      },
      startNum: 0,
      uploadingFilesNum: 0,
      uploadUrl: `${process.env.VUE_APP_BASE_API}/upload/uploadFile`,
      fileListPic: []
    }
  },
  methods: {
    beforePicUpload (file) {
      return this.beforeUpload(file)
    },
    beforeUpload (file) {
      this.uploadingFilesNum += 1
      return true
    },
    uploadPicSuccess (response, file, fileList) {
      this.uploadSuccess(response, file, fileList, 'enclosure')
    },
    uploadSuccess (response, file, fileList, fieldName) {
      this.uploadingFilesNum -= 1
      if (response.code === '200000') {
        let fileObj = {
          name: `${response.data.fileName}${response.data.fileExt}`,
          filePath: response.data.filePath,
          fileUrlPrefix: response.fileUrlPrefix
        }
        if (this.dialogForm[fieldName]) {
          let fileArr = JSON.parse(this.dialogForm[fieldName])
          fileArr.push(fileObj)
          let fileStr = JSON.stringify(fileArr)
          this.$set(this.dialogForm, fieldName, fileStr)
        } else {
          let fileStr = JSON.stringify([fileObj])
          this.$set(this.dialogForm, fieldName, fileStr)
        }
      }
    },
    handlePicPreview (file) {
      this.handlePreview(file, 'enclosure')
    },
    handlePreview (file, fileName) {
      if (file.response) {
        file = {
          name: `${file.response.data.fileName}${file.response.data.fileExt}`,
          filePath: file.response.data.filePath,
          fileUrlPrefix: file.response.fileUrlPrefix
        }
      }
      // 点击文件列表中已上传的文件时的钩子
      // window.location.href = `${process.env.VUE_APP_BASE_API}/upload/download?fileId=${file.fileId}`
      this.downFile(file)
    },
    handlePicRemove (file, fileList) {
      // 文件列表移除文件时的钩子
      this.handleRemove(file, fileList, 'enclosure')
    },
    handleRemove (file, fileList, fieldName) {
      if (file.status === 'uploading') {
        this.uploadingFilesNum -= 1
      }
      let fileArr = fileList.map((obj) => {
        if (obj.response) {
          return {
            name: `${obj.response.data.fileName}${obj.response.data.fileExt}`,
            filePath: obj.response.data.filePath,
            fileUrlPrefix: obj.response.fileUrlPrefix
          }
        }
        return {
          name: obj.name,
          filePath: obj.filePath,
          fileUrlPrefix: obj.fileUrlPrefix
        }
      })
      this.$set(this.dialogForm, fieldName, JSON.stringify(fileArr))
    },
    downFile(item) {
      let userPm = JSON.parse(localStorage.getItem('user_pm'))
      let url = userPm.fileUrlPrefix + item.filePath;
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          // 获取文件blob数据并保存
          this.saveAs(xhr.response, item.name);
        }
      };
      xhr.send();
    },
    saveAs(data, name) {
      var urlObject = window.URL || window.webkitURL || window;
      var export_blob = new Blob([data]);
      var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
      save_link.href = urlObject.createObjectURL(export_blob);
      save_link.download = name;
      save_link.click();
    },
    async getOrgListAndShow() {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          titleLike: this.formInline.titleLike.trim()
        }
        var res = await getCoreGuideList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    searchOrg() {
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    resetSearch() {
      for (let key in this.formInline) {
        this.$set(this.formInline, key, '')
      }
      this.currentPage = 1
      this.getOrgListAndShow()
    },
    popNewAddDialog() {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    selectionChange() {},
    pageChange (curPage) {
      this.currentPage = curPage
      this.startNum = (curPage - 1) * 10
      this.getOrgListAndShow()
    },
    showToDialog(res) {
      let data = res.data
      let content = data.content
      if (content) {
        let newContent = content.replace(/src="\//g, `src="${res.fileUrlPrefix}/`)
        data.content = newContent
      }
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.$set(this.dialogForm, key, data[key])
        }
      }
      this.fileListPic = []
      if (this.dialogForm.enclosure) {
        this.fileListPic = JSON.parse(this.dialogForm.enclosure)
      }
      Bus.$emit('setTinymceVal', this.dialogForm.content)
    },
    viewDetail(guideId) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getCoreGuideDetail({ guideId }).then((res) => {
        this.showToDialog(res)
      })
    },
    editDetail(guideId) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = guideId
      getCoreGuideDetail({ guideId }).then((res) => {
        this.showToDialog(res)
      })
    },
    deleteDetail(guideId) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteCoreGuide({ guideId }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getOrgListAndShow()
        })
      })
    },
    closeDialog() {
      Bus.$emit('setTinymceVal', '')
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.$set(this.dialogForm, key, '')
      }
      this.$refs.annex.clearFiles()
    },
    submitOrg() {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // 验证通过
          let requestData = deepClone(this.dialogForm)
          convertDateToString(requestData)
          let userPm = JSON.parse(localStorage.getItem('user_pm'))
          var patt=new RegExp(userPm.fileUrlPrefix, 'g')
          if (requestData.content) {
            let newContent = requestData.content.replace(patt, '')
            newContent = newContent.replace(/src="..\//g, 'src="/')
            requestData.content = newContent
          }
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            addCoreGuide(requestData).then((res) => {
              if (res.code === '200000') {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
                this.getOrgListAndShow()
                this.dialogFormVisible = false
              }
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.guideId = this.curId
            updateCoreGuide(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getOrgListAndShow()
              this.dialogFormVisible = false
            })
          }
        } else {
          return false
        }
      })
    }
  },
  mounted() {
    this.getOrgListAndShow()
  }
}
</script>

<style lang="scss" scoped>
.market-guide-wrapper {
  background-color: #ffffff;
  margin-top: 12px;
  border-radius: 4px;
  box-shadow: 0px 0px 22px -2px #d2d6da;
  padding: 20px;
  min-height: calc(100vh - 125px);
  .title {
    margin: 0;
    font-size: 15px;
    color: #333333;
    margin-bottom: 10px;
  }
  .form-search-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  .table-area {
    .el-link {
      margin-right: 13px;
    }
    .el-pagination.paging-self {
      margin-top: 20px;
      float: right;
    }
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-cascader,.el-select {
        width: 100%;
      }
      .el-date-editor--daterange.el-input__inner {
        width: 100%;
      }
      .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 100%;
      }
      /deep/.el-upload.el-upload--text {
        width: 100%;
        .el-button {
          width: 100%;
        }
      }
      .read-text {
        background-color: #f5f7fa;
        padding: 10px;
        border: 1px solid #eeeeee;
        overflow: auto;
      }
    }
  }
}
</style>
